<?php

namespace app\wechat\controller;

use app\common\controller\Base;
use Predis\Client;
use think\Config;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use app\enumerations\HandleStatusEnum;
use app\enumerations\CustomerVipEnum;
use app\enumerations\AccountDetailTypeEnum;
use app\enumerations\CustomerAccountLogTypeEnum;
use app\enumerations\IsSettlementEnum;
use app\enumerations\MissionTypeEnum;

class Test extends Base {


    public function testStat()
    {
        stateLessAsyncTask([
            "task_type" => "foreachCustomerEveryDayData"
        ]);
    }

    public function push() {

        $consumeCustomer = $this->customerService->findById(208);

        $redisConfig = config("constants.redis_config");
        $redisConfig["database"] = 1;

        $redisClient = new Client($redisConfig);
        $formId = popCustomerFormId($consumeCustomer["id"], $redisClient);

        if(!isNullOrEmpty($formId)) {

            // 发送模板消息
            $transactionData["openid"] = $consumeCustomer["openid"];
            $transactionData["page"] = "pages/index/index";
            $transactionData["form_id"] = $formId;
            $transactionData["goods_name"] = "呵呵";
            $transactionData["transaction_time"] = date("Y年m月d日 H:i:s");
            $transactionData["pay_amt"] = 123;
            $transactionData["tip"] = "🎉".$consumeCustomer["nickname"]."，恭喜你成功开启梦想中的赚钱小店！\n邀请更多好友来实现梦想，\n每成功邀请1名好友，即可获得200元现金创业基金！\n💰点击马上赚钱>>";

            sendTransactionReminding($transactionData);

        }



    }

    public function abc() {


        $orderService = $this->orderService;
        $orderId = "a166d8b22cebaa176345f992c588f04a";

        $order = $orderService->findById($orderId);

        if (isNullOrEmpty($order)) {
            return false;
        }

        $orderData["handle_status"] =
            HandleStatusEnum::getEnumValue(HandleStatusEnum::END_CODE);
        $orderData["handle_time"] = getCurrentTime();

        $customerService = $this->customerService;
        $firstCustomer = $customerService
            ->findByYxPid($order["pid"]);

        if(!isNullOrEmpty($firstCustomer)) {

            $firstCustomerId = $firstCustomer["id"];

            $orderData["customer_id"] = $firstCustomerId;

            $orderService->updateByIdAndData(
                $order["id"], $orderData);

            if (!isNullOrEmpty($order['unionid'])) {

                // 实际消费的人
                $consumeCustomer = $customerService
                    ->findByUnionid($order['unionid']);

                if(!isNullOrEmpty($consumeCustomer)) {

                    if($consumeCustomer["vip"] !=
                        CustomerVipEnum::getEnumValue(CustomerVipEnum::YES_CODE)) {
                        // 给实际消费的人设成vip
                        $consumeCustomerData['vip'] =
                            CustomerVipEnum::getEnumValue(CustomerVipEnum::YES_CODE);
                        $consumeCustomerData['parent_recommend_customer_id'] =
                            $firstCustomerId == $consumeCustomer["id"] ? 0 : $firstCustomerId;
                        $customerService->updateByIdAndData(
                            $consumeCustomer['id'], $consumeCustomerData);
                    }

                    if ($firstCustomer['vip']
                        == CustomerVipEnum::getEnumValue(CustomerVipEnum::YES_CODE)) {

                        $vipGoodsIdArr = explode(",",
                            config('constants.openVipGoodsId'));

                        // 如果实际消费的人购买的是开通会员的特定商品之一
                        if (in_array($order['goods_id'], $vipGoodsIdArr)) {

                            // 给推荐展位 加200
                            $firstCustomerData['history_profit'] =
                                $firstCustomer['history_profit']
                                + config('constants.recommendGiftMoney');
                            $firstCustomerData['total_assets'] =
                                $firstCustomer['total_assets']
                                + config('constants.recommendGiftMoney');
                            $firstCustomerData['recommend_number'] =
                                $firstCustomer['recommend_number'] + 1;

                            $customerService->updateByIdAndData(
                                $firstCustomerId, $firstCustomerData);

                            // 给推荐展位加流水
                            $accountDetailData['money'] = config('constants.recommendGiftMoney');
                            $accountDetailData['type'] = AccountDetailTypeEnum::getEnumValue(AccountDetailTypeEnum::RECOMMEND_CODE);
                            $accountDetailData['customer_id'] = $firstCustomerId;
                            $accountDetailData['refer_id'] = $order['id'];

                            $accountDetailService = $this->accountDetailService;
                            $accountDetailService->saveByData($accountDetailData);

                            // 推荐新人流水
                            $customerAccountLogData['customer_id'] = $firstCustomerId;
                            $customerAccountLogData['refer_customer_id'] = $firstCustomerId;
                            $customerAccountLogData['type'] = CustomerAccountLogTypeEnum::getEnumValue(CustomerAccountLogTypeEnum::RECOMMEND_CODE);
                            $customerAccountLogData['value'] = config('constants.recommendGiftMoney');
                            $customerAccountLogData['refer_id'] = $order['id'];

                            $customerAccountLogService = $this->customerAccountLogService;
                            $customerAccountLogService->saveByData($customerAccountLogData);

                        }
                    }
                }
            }
        }

    }

    public function runMission() {

        $missionCode = input("missionCode");

        asyncTask($missionCode);

    }

    public function calculateXdOrderSettle() {

        $orderService = $this->orderService;
        $missionService = $this->missionService;

        // 取出所有未处理订单
        $list = $orderService->getAllWaitingHandleList();

        Db::startTrans();

        try {

            $needNotHandleList = [];
            $missionDataList = [];
            foreach($list as $item) {

                if($item["is_settlement"] ==
                    IsSettlementEnum::getEnumValue(IsSettlementEnum::YES_CODE)) {

                    // 添加asyncIO处理的任务
                    $asyncMissionData["mission_code"] =
                        generateMissionCode();
                    $asyncMissionData["param"] = json_encode([
                        "task_type" => "calculateXdOrderSettleMoney",
                        "order_id" => $item["id"]
                    ]);
                    $asyncMissionData["mission_type"] =
                        MissionTypeEnum::getEnumValue(MissionTypeEnum::ASYNC_CODE);
                    array_push($missionDataList, $asyncMissionData);

                } else {

                    $needNotHandleInfo["id"] = $item["id"];
                    $needNotHandleInfo["handle_status"] =
                        HandleStatusEnum::getEnumValue(HandleStatusEnum::END_CODE);
                    $needNotHandleInfo["handle_time"] = getCurrentTime();

                    array_push($needNotHandleList, $needNotHandleInfo);

                    // 添加asyncIO处理的任务
                    $asyncMissionData["mission_code"] =
                        generateMissionCode();
                    $asyncMissionData["param"] = json_encode([
                        "task_type" => "preCalculateXdOrderSettleMoney",
                        "order_id" => $item["id"]
                    ]);
                    $asyncMissionData["mission_type"] =
                        MissionTypeEnum::getEnumValue(MissionTypeEnum::ASYNC_CODE);
                    array_push($missionDataList, $asyncMissionData);

                }

            }

            if(count($needNotHandleList) > 0) {
                $orderService->updateByList($needNotHandleList);
            }

            if(count($missionDataList) > 0) {
                $missionService->saveByList($missionDataList);
            }

            Db::commit();

        } catch (PDOException $exception) {

            Db::rollback();

            print_r($exception);
            exit();

        }

        // asyncIO处理
        foreach ($missionDataList as $missionItem) {
            asyncTask($missionItem["mission_code"]);
        }

    }

    public function index() {

        $pageNum = 1;
        $pageSize = 100;

        // 获取上次获取时间
        $lastTime = getXdLastPullTime();
        $now = getCurrentTime();

        if(isNullOrEmpty($lastTime)) {
            $lastTime = date("2018-08-01 00:00:00");
        }

        $mergeSuccess = $this->handleMergeXdOrder(
            $lastTime, $now, $pageNum, $pageSize);

        if($mergeSuccess) {
            setXdLastPullTime($now);
        }

    }

    public function handleMergeXdOrder(
        $startTime, $endTime, $pageNum, $pageSize) {

        $mergeSuccess = false;

        $result = yxOrderInfoByUpdateTime(
            $startTime, $endTime, $pageNum, $pageSize);

        if($result["success"]) {

            $mergeSuccess = true;

            $list = $result["data"]["list"];
            $count = $result["data"]["total"];

            $sqlList = [];
            foreach($list as $item) {

                array_push($sqlList,
                    generateXdOrderReplaceSql($item));

            }

            if(count($list) > 0) {
                Db::batchQuery($sqlList);
            }

            if($count > $pageSize*$pageNum) {

                $mergeSuccess = $this->handleMergeXdOrder(
                    $startTime, $endTime, ++$pageNum, $pageSize);

            }

        }

        return $mergeSuccess;

    }

}